package ruler.rules.activities;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;

public class AppsLists {

	public static String[] getInstalledApps(Context context) {
		final PackageManager pm = context.getPackageManager();
		List<ApplicationInfo> packages = pm
				.getInstalledApplications(PackageManager.GET_META_DATA);
		List<String> appsNames = new ArrayList<String>();
		for (ApplicationInfo appInfo : packages) {
			try {
				CharSequence c = pm.getApplicationLabel(pm.getApplicationInfo(
						appInfo.packageName, PackageManager.GET_META_DATA));
				appsNames.add(c.toString());
			} catch (Exception e) {
				appsNames.add(appInfo.packageName);
			}
		}
		String[] names = convert(appsNames);
		Arrays.sort(names);
		return names;
	}

	public static String[] getRunningServices(Context context) {
		ActivityManager activityManager = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningServiceInfo> runningServices = activityManager
				.getRunningServices(Integer.MAX_VALUE);
		List<String> appsNames = new ArrayList<String>();
		PackageManager pm = context.getPackageManager();
		for (RunningServiceInfo info : runningServices) {
			try {
				CharSequence c = pm.getApplicationLabel(pm.getApplicationInfo(
						info.process, PackageManager.GET_META_DATA));
				appsNames.add(c.toString());
			} catch (Exception e) {
				appsNames.add(info.service.getPackageName());
			}
		}
		String[] names = convert(appsNames);
		Arrays.sort(names);
		return names;
	}

	public static String[] getRunningApps(Context context) {
		ActivityManager activityManager = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningTaskInfo> runningTasks = activityManager
				.getRunningTasks(Integer.MAX_VALUE);
		List<String> appsNames = new ArrayList<String>();
		PackageManager pm = context.getPackageManager();
		for (RunningTaskInfo appInfo : runningTasks) {
			appsNames.add(appInfo.topActivity.getPackageName());
			try {
				CharSequence c = pm.getApplicationLabel(pm.getApplicationInfo(
						appInfo.topActivity.getPackageName(),
						PackageManager.GET_META_DATA));
				appsNames.add(c.toString());
			} catch (Exception e) {
				appsNames.add(appInfo.topActivity.getPackageName());
			}
		}
		String[] names = convert(appsNames);
		Arrays.sort(names);
		return names;
	}

	private static String[] convert(List<String> from) {
		ArrayList<String> list = new ArrayList<String>();
		for (String string : from) {
			Collections.addAll(list, string);
		}
		return list.toArray(new String[list.size()]);
	}

}
